#pragma once
#include <sys/epoll.h>
#include <unistd.h>
#include "log.hpp"

static const int LISTEN_FD_SIZE = 128;
class Epoller
{
public:
    Epoller()
    {
        _efd = epoll_create(LISTEN_FD_SIZE);
        if(_efd == -1)
        {
            LogMessage(DEBUG,"EPOLL_CREATE FAIL");
        }
        else
        {
            LogMessage(DEBUG,"EPOLL_CREATE SUCCESS");
        }
    }   
    int EpollerWait(struct epoll_event *events, int maxevents)
    {
        int wait_ret = epoll_wait(_efd,events,maxevents,_timeout);
        if(wait_ret == -1)
        {
            LogMessage(DEBUG,"EPOLL_WAIT FAIL");
        }
        return wait_ret;      
    }
    int EpollUpdata( int op, int fd, uint32_t event)
    {
        int ctl_ret =0;
        if(op == EPOLL_CTL_DEL)//del
        {
            ctl_ret = epoll_ctl(_efd,op,fd,nullptr);//删除时不需要关心event
            if(ctl_ret == -1)
            {
                LogMessage(DEBUG,"EPOLL_CTL DELETE FAIL");
            }
        }
        else//mod or add
        {
            struct epoll_event ev;
            ev.events = event;
            ev.data.fd = fd;

            ctl_ret = epoll_ctl(_efd,op,fd,&ev);
            if(ctl_ret == -1)
            {
                LogMessage(DEBUG,"EPOLL_CTL FAIL");
            }
        }
        return ctl_ret;
    }

    ~Epoller()
    {
        if(_efd >= 0)
        {
            close(_efd);
        }
    }
private:
    int _efd;//epoll实列的文件描述符
    int _timeout{1000};
};